package com.meilian.tbcrm.java.tmc.message;

import com.meilian.tbcrm.java.tmc.util.Config;
import com.meilian.tbcrm.java.tmc.util.JedisDataSource;
import com.meilian.tbcrm.java.tmc.util.StringKit;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 淘宝tmc客户端消息处理器
 *
 * 2017年10月28日15:23:46
 * @author 陈杰
 *
 */
public class TmcClientMessageHanlder implements MessageHandler {
    private Logger logger = LoggerFactory.getLogger(TmcClientMessageHanlder.class);

    /**
     * jedis连接池
     * */
    private JedisDataSource jedisDataSource;

    public TmcClientMessageHanlder(){
        //加载配置文件
        Config config = new Config("redis.properties");

        //实力化连接池
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(config.getInt("redis.pool.maxActive"));
        jedisPoolConfig.setMaxIdle(config.getInt("redis.pool.maxIdle"));
        jedisPoolConfig.setMaxWaitMillis(config.getInt("redis.pool.maxWaitMillis"));
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);

        //初始化jedis连接池
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,
                config.getString("redis.host"),
                config.getInt("redis.port"),
                config.getInt("redis.timeout"),
                config.getString("redis.password"),
                config.getInt("redis.database"));

        this.jedisDataSource = new JedisDataSource();
        this.jedisDataSource.setJedisPool(jedisPool);
    }


    @Override
    public void onMessage(Message message, MessageStatus status) throws Exception {
        Jedis jedis = null;
        try {
            jedis = jedisDataSource.getResource();

            String tb_message = message.getContent() ;
            int end_position = tb_message.indexOf("}");
            String tb_message_new = tb_message.substring(0, end_position) + ",\"topic\":"+"\"" +message.getTopic() + "\"}";
            if(StringKit.isNotBlank(tb_message_new)) {
                jedis.rpush("message", tb_message_new);
                logger.info("推送消息:({})",tb_message_new);
            }
        } catch (Exception e) {
            status.fail();
            logger.info("读取消息时出现异常,异常信息:{}",e.getMessage(),e);
        } finally {
            jedisDataSource.returnResource(jedis);
        }
    }


}
